package com.dhecp.project.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.*;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.finance.domain.AccountDetailedForCompany;
import com.dhecp.project.finance.mapper.AccountDetailedForCompanyMapper;
import com.dhecp.project.flowable.domain.SysProcessInstance;
import com.dhecp.project.flowable.mapper.SysProcessInstanceMapper;
import com.dhecp.project.flowable.service.ActProcessService;
import com.dhecp.project.hr.domain.OperateCompanyRoute;
import com.dhecp.project.hr.mapper.OperateCompanyRouteMapper;
import com.dhecp.project.storage.domain.OfflinePurchaseStorage;
import com.dhecp.project.storage.domain.PurchasingError;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.mapper.OfflinePurchaseStorageMapper;
import com.dhecp.project.storage.mapper.PurchasingErrorMapper;
import com.dhecp.project.storage.mapper.StockControlMapper;
import com.dhecp.project.storage.service.PurchasingErrorService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: kjecp
 * @description: 采购报错单
 * @author: hlf
 * @create: 2022-09-01 15:33
 */
@Service
public class PurchasingErrorServiceImpl extends BaseModuleServiceImpl implements PurchasingErrorService {


    @Autowired
    private PurchasingErrorMapper storageMapper;
    @Autowired
    private OfflinePurchaseStorageMapper offlinePurchaseStorageMapper;
    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;
    @Autowired
    private ActProcessService actProcessService;
    @Autowired
    private SysProcessInstanceMapper processInstanceMapper;
    @Autowired
    private StockControlMapper stockControlMapper;
    @Autowired
    private AccountDetailedForCompanyMapper accountDetailedForCompanyMapper;
    @Autowired
    private OperateCompanyRouteMapper operateCompanyRouteMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    /**
     * @Description: 查询前一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectLastNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询后一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectNextNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.PurchasingError
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public PurchasingError queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectFirstRecordByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.PurchasingError>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<PurchasingError> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectByNid(params);
    }


    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.PurchasingError>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<PurchasingError> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return storageMapper.select(params);
    }

    /**
     * @Description: 保存
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new PurchasingError());
        params.put("isAuto", false);
        AjaxResult ajaxResult = this.saveDataBase(params);
        if (!"0".equals(ajaxResult.get("code").toString())) {
            throw new RuntimeException(ajaxResult.get("msg").toString());
        }

        String resNid = "0";
        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        infoMap.put("state", infoMap.get("state") + "");
        List<PurchasingError> infoItems = JSON.parseArray(params.get("infoItems").toString(), PurchasingError.class);

        List<RecordCheck> guidMapList = storageMapper.findRecords(infoMap.get("nid").toString());
        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty() && guidMapList.size() > 0) {
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())) { //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList) {
                if (recordCheck != null && recordCheck.getGuid() != null) {
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }

        if (infoItems == null || infoItems.size() == 0) {
            resNid = "0";
        } else {
            resNid = infoMap.get("nid").toString();
            for (PurchasingError businessData : infoItems) {
                String guid = "";
                if (businessData.getGuid() == null) {
                    guid = RandomValueUtils.getGUID();
                    businessData.setGuid(guid);
                } else {
                    guid = businessData.getGuid().toString();
                }

                for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                    Object fieldValue = infoMap.get(field);
                    ReflectUtils.setValue(businessData, field, fieldValue);
                }

                if (guidMap.get(guid) == null) {
                    storageMapper.insert(businessData);
                } else {
                    businessData.setUpdateTime(new Date());
                    storageMapper.update(businessData);
                    guidMap.remove(guid);
                }
            }
        }

        if (!guidMap.isEmpty()) {
            for (String guid : guidMap.keySet()) {
                storageMapper.delete(guid);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), resNid);
    }

    /**
     * @Description: 删除
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<PurchasingError> businessDataList = JSON.parseArray(params.get("infoItems").toString(), PurchasingError.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (PurchasingError businessData : businessDataList) {
            storageMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 修改删除标志（预留）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
            storageMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<PurchasingError> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (PurchasingError businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * @Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<PurchasingError> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (PurchasingError businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }


    /**
     * 修改审核状态
     *
     * @param params
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateType(Map<String, Object> params) {
        List<PurchasingError> purchasingErrors = JSON.parseArray(params.get("infoItems").toString(), PurchasingError.class);
        for (PurchasingError item : purchasingErrors
        ) {
            Map<String, Object> paramsError = new HashMap<String, Object>();
            paramsError.put("nid", item.getNid());
            List<PurchasingError> purchasingErrorList = storageMapper.selectByNid(paramsError);

            if (item.getState().equals("3") && purchasingErrorList.get(0).getState().equals("2")) {
                //当流程是从采购处理到已完成
                item.setEffectStock(true);
                for (PurchasingError item2 : purchasingErrorList
                ) {
                    //判断当前处理类型
                    if (item2.getDispose().equals("补入")) {//当处理方式为补入的时候需要生成新库存
                        StockControl newStock = new StockControl();
                        newStock = new StockControl();
                        newStock.setGuid(RandomValueUtils.getGUID());
                        newStock.setProductNum(item2.getProductNum());//可用数量
                        newStock.setProductNumAll(item2.getProductNum());//库存总数
                        newStock.setRkGuid(item2.getGuid());//入库标识
                        newStock.setRkBid(item2.getNid());//入库单号
                        newStock.setIsParent("0");//是否母件
                        newStock.setvHw(item2.getvHw());//入库货位
                        newStock.setvKq(item2.getvKq());//库区
                        newStock.setgDepot(item2.getgDepot());//所在仓库
                        newStock.setvGsBm(item2.getvGsBm());//公司编码
                        newStock.setvGsJc(item2.getvGsJc());//公司简称
                        newStock.setvGsMc(item2.getvGsMc());//公司名称
                        newStock.setProductCode(item2.getSonCode());//商品编码
                        newStock.setProductName(item2.getSonName());
                        ;//商品名称
                        newStock.setPurchasePrice(item2.getSonPrice());//商品采购价
                        newStock.setPurchaseTotalPriceAll(item2.getSonPrice() * item2.getProductNum());//采购总价
                        newStock.setAllotPrice(0.00);//调拨单价
                        newStock.setTotalAllotPrice(0.00);//调拨总价
                        newStock.setsDays(0);//库存天数
//                    newStock.setAssembleID(item2.getAssembleID());//组装单
                        newStock.setPurchaseStorageID(item2.getNid());//采购入库单
                        newStock.setPurchaseOrderID(item2.getOrderID());//采购订单
                        newStock.setPurchasePlanID(item2.getOrderID());//采购计划单
                        newStock.setdRkSj(new Date());//入库日期
                        newStock.setCreateTime(new Date());//创建日期
                        stockControlMapper.insert(newStock);
                    }

                }
                if (purchasingErrorList.get(0).getDispose().equals("赔偿")) {//当处理方式为赔偿时需要生成流水

                    List<PurchasingError> newPurchasingError = new ArrayList<>();
                    newPurchasingError = purchasingErrorList.stream()
                            .collect(Collectors.groupingBy(PurchasingError::getvGsBm2))
                            .values()
                            .stream()
                            .map(this::mergeDataList)
                            .collect(Collectors.toList());

                    for (PurchasingError item2 : newPurchasingError
                    ) {
                        //判断当前处理类型
                        //赔偿对象
                        OperateCompanyRoute operateCompanyRoute1 = operateCompanyRouteMapper.findByGsBm(item2.getvGsBm());
                        OperateCompanyRoute operateCompanyRoute2 = operateCompanyRouteMapper.findByGsBm(item2.getvGsBm2());
                        AccountDetailedForCompany accountDetailedForCompany = new AccountDetailedForCompany();
                        accountDetailedForCompany.setGuid(RandomValueUtils.getGUID());//唯一标识
                        accountDetailedForCompany.setvGsBm(operateCompanyRoute1.getvGsBm());//公司编码
                        accountDetailedForCompany.setvGsJc(operateCompanyRoute1.getvGsJc());//公司简称
                        accountDetailedForCompany.setvGsMc(operateCompanyRoute1.getvGsMc());//公司名称
                        accountDetailedForCompany.setvGsBmP(operateCompanyRoute2.getvGsBm());//对方编码
                        accountDetailedForCompany.setvGsJcP(operateCompanyRoute2.getvGsJc());//对方简称
                        accountDetailedForCompany.setvGsMcP(operateCompanyRoute2.getvGsMc());//对方名称
                        accountDetailedForCompany.setfJe(item2.getSalesReturnSum());//交易金额
                        accountDetailedForCompany.setvJyLx("运营服务→经营理赔款项");//交易类型
                        accountDetailedForCompany.setdJySj(new Date());//登记日期
                        accountDetailedForCompany.setdShSj(new Date());//审核日期
                        accountDetailedForCompany.setvBz("报错单：" + item2.getBid() + "，采购订单：" + item2.getOrderID() + "，商品编码：" + item2.getProductID() + "，商品名称：" + item2.getProductName());// 备注
                        accountDetailedForCompany.setCreateTime(new Date());//创建日期
                        accountDetailedForCompany.setWriteTime(new Date());//记账时间
                        accountDetailedForCompany.setmName("采购报错");
                        accountDetailedForCompany.setmType(1);
                        accountDetailedForCompany.setmGuid(item2.getGuid());
                        accountDetailedForCompany.setmNid(item2.getNid());
                        accountDetailedForCompany.setmBid(item2.getBid());

                        accountDetailedForCompany.setOperatorDept(operateCompanyRoute1.getOperatorDept());//运营部门
                        accountDetailedForCompany.setOperatorName(operateCompanyRoute1.getOperatorName());//运营人姓名
                        accountDetailedForCompany.setOperatorUserId(operateCompanyRoute1.getOperatorUserId());//运营人工号
                        accountDetailedForCompany.setOperatorPosition(operateCompanyRoute1.getOperatorPosition());//运营岗位
                        accountDetailedForCompanyMapper.insertAccountDetailedForCompany(accountDetailedForCompany);

                        //赔偿公司
                        AccountDetailedForCompany accountDetailedForCompany2 = new AccountDetailedForCompany();
                        accountDetailedForCompany2.setGuid(RandomValueUtils.getGUID());//唯一标识
                        accountDetailedForCompany2.setvGsBm(operateCompanyRoute2.getvGsBm());//公司编码
                        accountDetailedForCompany2.setvGsJc(operateCompanyRoute2.getvGsJc());//公司简称
                        accountDetailedForCompany2.setvGsMc(operateCompanyRoute2.getvGsMc());//公司名称
                        accountDetailedForCompany2.setvGsBmP(operateCompanyRoute1.getvGsBm());//对方编码
                        accountDetailedForCompany2.setvGsJcP(operateCompanyRoute1.getvGsJc());//对方简称
                        accountDetailedForCompany2.setvGsMcP(operateCompanyRoute1.getvGsMc());//对方名称
                        accountDetailedForCompany2.setfJe(-item2.getSalesReturnSum());//交易金额
                        accountDetailedForCompany2.setvJyLx("运营服务→经营理赔款项");//交易类型
                        accountDetailedForCompany2.setdJySj(new Date());//登记日期
                        accountDetailedForCompany2.setdShSj(new Date());//审核日期
                        accountDetailedForCompany2.setvBz("报错单：" + item2.getBid() + "，采购订单：" + item2.getOrderID() + "，商品编码：" + item2.getProductID() + "，商品名称：" + item2.getProductName());// 备注
                        accountDetailedForCompany2.setCreateTime(new Date());//创建日期
                        accountDetailedForCompany2.setWriteTime(new Date());//记账时间
                        accountDetailedForCompany2.setmName("采购报错");
                        accountDetailedForCompany2.setmType(1);
                        accountDetailedForCompany2.setmGuid(item2.getGuid());
                        accountDetailedForCompany2.setmNid(item2.getNid());
                        accountDetailedForCompany2.setmBid(item2.getBid());

                        accountDetailedForCompany2.setOperatorDept(operateCompanyRoute2.getOperatorDept());//运营部门
                        accountDetailedForCompany2.setOperatorName(operateCompanyRoute2.getOperatorName());//运营人姓名
                        accountDetailedForCompany2.setOperatorUserId(operateCompanyRoute2.getOperatorUserId());//运营人工号
                        accountDetailedForCompany2.setOperatorPosition(operateCompanyRoute2.getOperatorPosition());//运营岗位
                        accountDetailedForCompanyMapper.insertAccountDetailedForCompany(accountDetailedForCompany2);
                    }

                }
                if (purchasingErrorList.get(0).getDispose().equals("货物补发")) {//当处理方式为赔偿时需要生成流水
                    createStockIn(purchasingErrorList.get(0));
                }

            } else if (item.getState().equals("2") && purchasingErrorList.get(0).getState().equals("3")) {
                //当流程是从已完成退回到采购处理
                item.setEffectStock(false);

                for (PurchasingError item2 : purchasingErrorList
                ) {
                    StockControl newStock = new StockControl();//生成新的库存数据
                    if (item2.getDispose().equals("补入")) {//当处理方式为补入的时候需要删除库存
                        //判断是否存在库存数据
                        Map<String, Object> params2 = new HashMap<String, Object>();
                        params2.put("rkGuid", item2.getGuid());
                        params2.put("vGsBm", item2.getvGsBm());
                        params2.put("vHw", item2.getvHw());
                        params2.put("vKq", item2.getvKq());
                        params2.put("gDepot", item2.getgDepot());
                        params2.put("productcode", item2.getSonCode());
                        newStock = stockControlMapper.findByMultiparameter(params2);
                        if (newStock != null) {//还原库存
                            //删除库存信息
                            stockControlMapper.deleteStockControl(newStock.getGuid());
                        }
                    }
                }

                if (purchasingErrorList.get(0).getDispose().equals("赔偿")) {//当处理方式为赔偿时需要生成流水
                    List<PurchasingError> newPurchasingError = new ArrayList<>();
                    newPurchasingError = purchasingErrorList.stream()
                            .collect(Collectors.groupingBy(PurchasingError::getvGsBm2))
                            .values()
                            .stream()
                            .map(this::mergeDataList)
                            .collect(Collectors.toList());

                    for (PurchasingError item2 : newPurchasingError
                    ) {
                        //赔偿对象
                        OperateCompanyRoute operateCompanyRoute1 = operateCompanyRouteMapper.findByGsBm(item2.getvGsBm());
                        OperateCompanyRoute operateCompanyRoute2 = operateCompanyRouteMapper.findByGsBm(item2.getvGsBm2());
                        AccountDetailedForCompany accountDetailedForCompany = new AccountDetailedForCompany();
                        accountDetailedForCompany.setGuid(RandomValueUtils.getGUID());//唯一标识
                        accountDetailedForCompany.setvGsBm(operateCompanyRoute1.getvGsBm());//公司编码
                        accountDetailedForCompany.setvGsJc(operateCompanyRoute1.getvGsJc());//公司简称
                        accountDetailedForCompany.setvGsMc(operateCompanyRoute1.getvGsMc());//公司名称
                        accountDetailedForCompany.setvGsBmP(operateCompanyRoute2.getvGsBm());//对方编码
                        accountDetailedForCompany.setvGsJcP(operateCompanyRoute2.getvGsJc());//对方简称
                        accountDetailedForCompany.setvGsMcP(operateCompanyRoute2.getvGsMc());//对方名称
                        accountDetailedForCompany.setfJe(-item2.getSalesReturnSum());//交易金额
                        accountDetailedForCompany.setvJyLx("运营服务→经营理赔款项");//交易类型
                        accountDetailedForCompany.setdJySj(new Date());//登记日期
                        accountDetailedForCompany.setdShSj(new Date());//审核日期
                        accountDetailedForCompany.setvBz("（退回）报错单：" + item2.getBid() + "，采购订单：" + item2.getOrderID() + "，商品编码：" + item2.getProductID() + "，商品名称：" + item2.getProductName());// 备注
                        accountDetailedForCompany.setCreateTime(new Date());//创建日期
                        accountDetailedForCompany.setWriteTime(new Date());//记账时间
                        accountDetailedForCompany.setmName("采购报错");
                        accountDetailedForCompany.setmType(1);
                        accountDetailedForCompany.setmGuid(item2.getGuid());
                        accountDetailedForCompany.setmNid(item2.getNid());
                        accountDetailedForCompany.setmBid(item2.getBid());

                        accountDetailedForCompany.setOperatorDept(operateCompanyRoute1.getOperatorDept());//运营部门
                        accountDetailedForCompany.setOperatorName(operateCompanyRoute1.getOperatorName());//运营人姓名
                        accountDetailedForCompany.setOperatorUserId(operateCompanyRoute1.getOperatorUserId());//运营人工号
                        accountDetailedForCompany.setOperatorPosition(operateCompanyRoute1.getOperatorPosition());//运营岗位
                        accountDetailedForCompanyMapper.insertAccountDetailedForCompany(accountDetailedForCompany);

                        //赔偿公司
                        AccountDetailedForCompany accountDetailedForCompany2 = new AccountDetailedForCompany();
                        accountDetailedForCompany2.setGuid(RandomValueUtils.getGUID());//唯一标识
                        accountDetailedForCompany2.setvGsBm(operateCompanyRoute2.getvGsBm());//公司编码
                        accountDetailedForCompany2.setvGsJc(operateCompanyRoute2.getvGsJc());//公司简称
                        accountDetailedForCompany2.setvGsMc(operateCompanyRoute2.getvGsMc());//公司名称
                        accountDetailedForCompany2.setvGsBmP(operateCompanyRoute1.getvGsBm());//对方编码
                        accountDetailedForCompany2.setvGsJcP(operateCompanyRoute1.getvGsJc());//对方简称
                        accountDetailedForCompany2.setvGsMcP(operateCompanyRoute1.getvGsMc());//对方名称
                        accountDetailedForCompany2.setfJe(item2.getSalesReturnSum());//交易金额
                        accountDetailedForCompany2.setvJyLx("运营服务→经营理赔款项");//交易类型
                        accountDetailedForCompany2.setdJySj(new Date());//登记日期
                        accountDetailedForCompany2.setdShSj(new Date());//审核日期
                        accountDetailedForCompany2.setvBz("（退回）报错单：" + item2.getBid() + "，采购订单：" + item2.getOrderID() + "，商品编码：" + item2.getProductID() + "，商品名称：" + item2.getProductName());// 备注
                        accountDetailedForCompany2.setCreateTime(new Date());//创建日期
                        accountDetailedForCompany2.setWriteTime(new Date());//记账时间
                        accountDetailedForCompany2.setmName("采购报错");
                        accountDetailedForCompany2.setmType(1);
                        accountDetailedForCompany2.setmGuid(item2.getGuid());
                        accountDetailedForCompany2.setmNid(item2.getNid());
                        accountDetailedForCompany2.setmBid(item2.getBid());

                        accountDetailedForCompany2.setOperatorDept(operateCompanyRoute2.getOperatorDept());//运营部门
                        accountDetailedForCompany2.setOperatorName(operateCompanyRoute2.getOperatorName());//运营人姓名
                        accountDetailedForCompany2.setOperatorUserId(operateCompanyRoute2.getOperatorUserId());//运营人工号
                        accountDetailedForCompany2.setOperatorPosition(operateCompanyRoute2.getOperatorPosition());//运营岗位
                        accountDetailedForCompanyMapper.insertAccountDetailedForCompany(accountDetailedForCompany2);
                    }
                }

            } else {
                item.setEffectStock(false);
            }
            item.setUpdateTime(new Date());
            storageMapper.updateType(item);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }


    //生成 入库单  TCG_OfflinePurchaseStorage
    public void createStockIn(PurchasingError purchasingError) {

        //判断是否已生成线下采购入库单
        List<OfflinePurchaseStorage> old = offlinePurchaseStorageMapper.selectPlanID2(purchasingError.getBid());
        if (old.size() == 0) {
            int iid = 0;

            Map<String, Object> params2 = new HashMap<>();
            params2.put("nid", purchasingError.getNid());
            List<PurchasingError> purchasingErrorList = storageMapper.selectByNid(params2);

            String moduleTable = "TCG_OfflinePurchaseStorage";
            String moduleName = "线下入库单";
            OfflinePurchaseStorage offlinePurchaseStorage = new OfflinePurchaseStorage();
            Map<String, Object> params = new HashMap<>();

            params.put("moduleTable", moduleTable);
            ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params);    //有事务控制，制单异常不跳过单号

            for (PurchasingError item : purchasingErrorList
            ) {
                if (item.getDispose().equals("货物补发")) {//生成 入库单

                    //基础信息
                    offlinePurchaseStorage.setNid(moduleNidAndBid.getNid());
                    offlinePurchaseStorage.setBid(moduleNidAndBid.getBid());
                    offlinePurchaseStorage.setCreateTime(new Date());
                    offlinePurchaseStorage.setCid(ShiroUtils.getMandatorCid());
                    offlinePurchaseStorage.setCidName(ShiroUtils.getMandatorCidName());
                    offlinePurchaseStorage.setbUser(ShiroUtils.getMandatorId());
                    offlinePurchaseStorage.setbUserName(ShiroUtils.getMandatorName());
                    offlinePurchaseStorage.setbDept(ShiroUtils.getMandatorDeptPath());
                    offlinePurchaseStorage.setbDeptName(ShiroUtils.getMandatorDeptName());
                    offlinePurchaseStorage.setbPosition(ShiroUtils.getMandatorPositionNameDa());
                    offlinePurchaseStorage.setaUser(ShiroUtils.getUserId());
                    offlinePurchaseStorage.setaUserName(ShiroUtils.getUserName());
                    offlinePurchaseStorage.setaDept(ShiroUtils.getUserDeptPath());
                    offlinePurchaseStorage.setaDeptName(ShiroUtils.getUserDeptName());
                    offlinePurchaseStorage.setaPosition(ShiroUtils.getUserPositionNameDa());
                    offlinePurchaseStorage.setEffectStock(false);//是否生效
                    offlinePurchaseStorage.setDeleted(false);//是否删除
                    offlinePurchaseStorage.setActiveFlow("FlowZd");//流程状态
                    offlinePurchaseStorage.setIid(iid);//iid
//        offlinePurchaseStorage.setvZdbz("采购报错入库");//单据备注
                    //调拨信息
                    offlinePurchaseStorage.setName(item.getProductName());//商品名称
                    offlinePurchaseStorage.setCode(item.getProductID());//商品编码
                    offlinePurchaseStorage.setsCode(item.getSonCode());//子商品编码
                    offlinePurchaseStorage.setsName(item.getSonName());//子商品名称
                    offlinePurchaseStorage.setsNum(item.getSonNum());//商品采购数量
                    offlinePurchaseStorage.setInqty(item.getSonNum());//商品到货数量
                    offlinePurchaseStorage.setNinqty(item.getSonNum());//商品未到货数量

                    offlinePurchaseStorage.setPlanID(item.getBid());//采购计划单号
                    offlinePurchaseStorage.setpGuid(item.getGuid());//父标识
                    offlinePurchaseStorage.setOrderID(item.getOrderID());//采购订单单号
                    offlinePurchaseStorage.setTrackingNumber(item.getLogisticsID1());//物流单号
                    offlinePurchaseStorage.setPlace(item.getLogisticsChannel1());//物流渠道
                    offlinePurchaseStorage.setState("未入库");//入库状态
                    offlinePurchaseStorage.setInqty(0);//商品到货数量
                    offlinePurchaseStorage.setNinqty(item.getSonNum());//商品未到货数量

                    offlinePurchaseStorage.setvGsJc(item.getvGsJc());//所属公司简称
                    offlinePurchaseStorage.setvGsMc(item.getvGsMc());//所属公司名称
                    offlinePurchaseStorage.setvGsBm(item.getvGsBm());//所属公司编码
//
                    //生成流程信息
                    AjaxResult ajaxResult = AjaxResult.success();
                    SysProcessInstance sysProcessInstance = new SysProcessInstance();
                    String processTitle = moduleName + "(" + moduleNidAndBid.getBid() + ")";
                    String procDefKey = moduleTable;
                    String tableDataId = moduleNidAndBid.getNid().toString();
                    sysProcessInstance.setProcessTitle(processTitle);
                    sysProcessInstance.setProcDefKey(procDefKey);
                    sysProcessInstance.setTableDataId(tableDataId);
//        sysProcessInstance.setProcessRemark("");
                    sysProcessInstance.setCorpNo(ShiroUtils.getMandatorCid());
                    sysProcessInstance.setCorpName(ShiroUtils.getMandatorCidName());
                    ajaxResult = actProcessService.startProcess(sysProcessInstance);
                    if ("0".equals(ajaxResult.get("code").toString())) {
                        if ("flowzd".equals(sysProcessInstance.getNextActAlias().toString().toLowerCase())) {
                            //插入指定单据流转各环节审批人记录
                            Map<String, Object> flowRecord = new HashMap<String, Object>();
                            flowRecord.put("moduleTable", moduleTable);
                            flowRecord.put("nid", tableDataId);
                            flowRecord.put("activeFlowOld", sysProcessInstance.getNextActAlias());
                            flowRecord.put("activeFlow", sysProcessInstance.getNextActAlias());
                            flowRecord.put("activeFlowName", sysProcessInstance.getNextActAlias());
                            flowRecord.put("procInstId", sysProcessInstance.getProcInstId());
                            flowRecord.put("createUser", ShiroUtils.getMandatorId());
                            flowRecord.put("createUserName", ShiroUtils.getMandatorName());
                            flowRecord.put("updateUsers", ShiroUtils.getMandatorId());
                            flowRecord.put("optType", "add");
                            processInstanceMapper.insertProcessInstanceFlowRecord(flowRecord);
                        } else {
                            throw new RuntimeException(MessageUtils.message("flowable.model.error.modelflowzdfail"));
                        }
                    }
                    offlinePurchaseStorage.setProcInstId(sysProcessInstance.getProcInstId());
                    offlinePurchaseStorageMapper.insert(offlinePurchaseStorage);//生成线下入库单
                    iid ++;
                }

            }
        }

//        return AjaxResult.success("操作成功，已生成入库单请及时确认!");
    }


    // 合并相同键名的数据
    public PurchasingError mergeDataList(List<PurchasingError> dataList) {
        PurchasingError purchasingError = new PurchasingError();
        double cost = 0.00;
        for (PurchasingError item : dataList
        ) {
            cost = cost + item.getSalesReturnSum();
        }
        purchasingError = dataList.get(0);
        purchasingError.setSalesReturnSum(cost);

        return purchasingError;
    }

}
